<script>
import { createTools, getToolID, updateTools } from '@/api/tool.js'
// import outputEdit from "@/components/AppCreate/output/outputEdit.vue";
import JsonCodeMirror from '@/components/JavascriptCodemirror/index.vue'
import JsonEditor from 'vue-json-editor'
export default {
  name: 'EditTool',
  components: {
    json_code: JsonCodeMirror,
    JsonEditor
  },
  data() {
    return {
      // 确认类型，是修改还是新建
      isEdit: false,
      // 要修改的id
      id: '',
      // 表单内容
      toolForm: {
        source:'',
        header: 
        `{
  "aaaaaa": "aaaaaa",
  "bbbbbb": "bbbbbb"    
}`,
        body: 
        `{
  "cccccc": "cccccc",
  "dddddd": "dddddd"  
}`,
        output_structure: 
        `{
  "result": "工具返回的结果"
}`,
        parameters: 
        `[
  {
    "description": "对参数的说明",
    "name": "变量名",
    "type": "变量类型，如：string",
    "value": "变量的默认值"
  }
]`,
        url: 'xxxxxx=xxxxxx&yyyyyy=yyyyyy'
      },
      // 参数可选类型
      paraType: [
        'string',
        'integer',
        'boolean',
        'text'
      ],
      value: '',
      param_handle: [
        {value: 'query', lable: 'query', comment: '参数全部拼接进url中'},
        {value: 'body', lable: 'body', comment: '参数全部写进请求体中'},
        {value: 'llm', lable: 'llm', comment: '适配普通llm接口形式'},
        {value: 'llm-image', lable: 'llm-image', comment: '适配图生文形式llm接口'},
        {value: 'generate-image', lable: 'generate-image', comment: '适配文生图形式llm接口'}
      ],
      // 表单提交时验证
      rules: {
        /*
        name: [
          { required: true, message: this.$t('container_new_name_rule'), trigger: 'blur' },
          { validator: validateName, trigger: 'blur' }
        ],
        type: [
          { required: true, message: this.$t('container_new_type_rule'), trigger: 'change' }
        ]*/
        name: [
          { required: true, message: ('工具名称不能为空!!!'), trigger: 'blur' }
        ],
        description: [
          { required: true, message: ('工具描述不能为空!!!'), trigger: 'change' }
        ],
        host: [
          { required: true, message: ('主机域名不能为空!!!'), trigger: 'blur' }
        ],
        // scenario: [
        //   { required: true, message: ('工具场景不能为空!!!'), trigger: 'change' }
        // ],
        method: [
          { required: true, message: ('请至少选择一个工具方法!!!'), trigger: 'blur' }
        ],
        param_handle: [
          { required: true, message: ('请至少选择一种参数处理方法!!!'), trigger: 'blur' }
        ],
        // output_name: [
        //   { required: true, message: ('工具的输出名称不能为空!!!'), trigger: 'blur' }
        // ],
        // output_description: [
        //   { required: true, message: ('工具的输出描述不能为空!!!'), trigger: 'change' }
        // ]
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      // 强制重置滚动位置
      window.scrollTo({ top: 0, behavior: 'auto' })
      // 同时移除编辑器焦点
      document.activeElement?.blur()
    })
  },
  /*
  computed: {
    parameters: {
      get() {
        return this.toolForm.parameters ? JSON.stringify(this.toolForm.parameters) : ''
      },
      set(val) {
      }
    }
  },*/
  created() {
    // 添加权限校验逻辑
    if (!this.$store.getters.isAdmin()) {
      this.$message({
        type: 'error',
        message: '您没有权限访问此页面'
      });
      this.$router.push('/');
      return;
    }
    this.id = this.$route.query.id
    this.isEdit = this.$route.query.is_edit
    if (this.isEdit) {
      // 若是编辑 请求工具内容并填入表格中
      getToolID(this.id).then(response => {
        console.log(response.data)
        const data = response
        console.log(data)
        this.toolForm = Object.assign({}, data)
        // 调整host的内容
        // this.toolForm.host = this.toolForm.host.slice(8)
        /* this.$message({
          message: '获取成功',
          type: 'success'
        }) */
        // 需要将输出结构和参数序列化以展示
        this.toolForm.output_structure = JSON.stringify(this.toolForm.output_structure, null, 2)
        this.toolForm.parameters = JSON.stringify(this.toolForm.parameters, null, 2)
        // this.toolForm.url = this.toolForm.url.split('?')[1]
        // 初始化param为空map
        if (!('params' in this.toolForm)) {
          this.$set(this.toolForm, 'params', [])
        }
      }).catch(error => {
        console.log(error)
        this.$message({
          message: '获取失败',
          type: 'error'
        })
      })
    }
  },
  methods: {
    // 添加参数
    pushPara() {
      if (!('parameters' in this.toolForm)) {
        this.$set(this.toolForm, 'parameters', [])
      }
      this.toolForm.parameters.push(
        {
          name: '',
          description: '',
          type: '',
          tool_id: 0,
          value: ''
        }
      )
      console.log(this.toolForm.parameters)
    },
    // 删除参数
    popPara(index) {
      this.toolForm.parameters.splice(index, 1)
    },
    // 保存按钮 提交表单
    submitForm() {
      this.$refs.toolForm.validate(valid => {
        if (!valid) {
          // 校验失败
        } else {
          // 进行tool的修改或新建
          let tool = {
            'name': this.toolForm.name,
            'description': this.toolForm.description,
            'host': this.toolForm.host,
            'source': this.toolForm.source,
            // 'scenario': this.toolForm.scenario,
            'method': this.toolForm.method,
            'params': this.toolForm.params,
            "param_handle": this.toolForm.param_handle,
            // 'output_name': this.toolForm.output_name,
            // 'output_description': this.toolForm.output_description,
            'parameters': JSON.parse(this.toolForm.parameters), // 这里需要进行反序列化
            'output_structure': JSON.parse(this.toolForm.output_structure), // 这里一样
            'url': this.toolForm.url,
            'header': this.toolForm.header,
            'body': this.toolForm.body,
          }
          if (this.isEdit) {
            // 编辑时要加上id
            tool['id'] = this.id
          } else {
            // 新建时要加上creator_id和created_at
            tool['creator_id'] = this.$store.getters.id;
            tool['created_at'] = this.toolForm.created_at;
          }
          // tool = JSON.stringify(tool)
          console.log(tool)
          if (this.isEdit) {
            updateTools(tool).then(response => {
              console.log(response.data)
              // 修改成功后返回上一界面
              this.$router.push({ path: '/tool/index' })
              /* this.$message({
                message: '修改成功',
                type: 'success'
              }) */
            }).catch(error => {
              console.log(error)
              this.$message({
                message: '修改失败',
                type: 'error'
              })
            })
          } else {
            createTools(tool).then(response => {
              console.log(response.data)
              // 创建成功后返回上一界面
              this.$router.push({ path: '/tool/index' })
              /* this.$message({
                message: '创建成功',
                type: 'success'
              }) */
            }).catch(error => {
              console.log(error)
              this.$message({
                message: '创建失败',
                type: 'error'
              })
            })
          }
        }
      })
    },

    handleAddParam() {
        this.toolForm.params.push({
          name: '',
          value: '',
          type: '',
          description: ''
        });
    },
    handleDeleteParam(index) {
      this.toolForm.params.splice(index, 1);
    },
    handleAddHeader() {
      this.toolForm.headers.push({ name: '', value: '' });
    },
    handleDeleteHeader(index) {
      this.toolForm.headers.splice(index, 1);
    },
  }
}
</script>

<template>
  <div class="app-container">
    <div class="create-container">
      <el-form ref="toolForm" :model="toolForm" :rules="rules" label-width="120px">
        <el-row type="flex" justify="center">
          <el-col :span="16">
            <!-- tool的名称 -->
            <el-row>
              <el-col :span="16">
                <el-form-item :label="$t('name')" prop="name">
                  <el-input v-model="toolForm.name" />
                </el-form-item>
              </el-col>
            </el-row>
            <!-- tool的描述 -->
            <el-form-item :label="$t('description')" prop="description">
              <el-input v-model="toolForm.description" :rows="4" type="textarea" :placeholder="$t('please')+$t('fill_in')+$t('description')" />
            </el-form-item>
            <!-- tool的来源 -->
            <el-form-item :label="$t('source')" prop="source">
              <el-input v-model="toolForm.source" type="text" />
            </el-form-item> 
            <!-- tool的主机域名 -->
            <el-form-item :label="$t('host')" prop="host">
              <el-input v-model="toolForm.host" type="text" />
            </el-form-item>
            <!-- tool的应用场景 -->
            <!-- <el-form-item :label="$t('scenario')" prop="scenario">
              <el-input v-model="toolForm.scenario" type="textarea" :placeholder="$t('please')+$t('fill_in')+'工具使用时的场景'" />
            </el-form-item> -->
            <!-- tool的请求方法 -->
            <el-form-item :label="$t('method')" prop="method">
              <el-radio-group v-model="toolForm.method">
                <el-radio label="get" />
                <el-radio label="put" />
                <el-radio label="delete" />
                <el-radio label="post" />
              </el-radio-group>
            </el-form-item>
            <!-- tool的参数处理 -->
            <!-- <el-form-item :label="$t('parameter') + $t('handle')" prop="param_handle">
              <el-select
                v-model="toolForm.param_handle"
                placeholder="请选择"
                style="width: 30%"
              >
                <el-option
                  v-for="item in param_handle"
                  :key="item.value"
                  :label="item.lable"
                  :value="item.value">
                  <el-tooltip :content="item.comment" placement="top">
                    <span>{{ item.lable }}</span>
                  </el-tooltip>
                </el-option>
              </el-select>
            </el-form-item>
            <!-- 输出名称 -->
            <!-- <el-form-item label="output_name" prop="output_name">
              <el-input v-model="toolForm.output_name" type="text" placeholder="请填写工具的输出名称" />
            </el-form-item> -->
            <!-- 输出描述 -->
            <!-- <el-form-item label="output_desc" prop="output_description">
              <el-input v-model="toolForm.output_description" type="textarea" placeholder="请填写工具的输出描述" />
            </el-form-item> -->
            <!-- 可选的参数填写 -->
            <el-form-item :label="$t('Input_parameter')" prop="parameters">
              <json_code v-model="toolForm.parameters" />
              <!--json-editor v-model="toolForm.parameters" mode="code" :show-btns="false" lang="json" /-->
            </el-form-item>
            <el-form-item :label="$t('Output_parameter')" prop="parameters">
              <json_code v-model="toolForm.output_structure" />
              <!--json-editor v-model="toolForm.output_structure" mode="code" :show-btns="false" lang="zh" /-->
            </el-form-item>

            <!-- 动态添加query参数 -->
            <el-form-item :label="''" prop="url">
              <template slot="label">
                入参适配<br>（URL）
              </template>
              <json_code v-model="toolForm.url" />
              <!-- <el-table :data="toolForm.params" style="width: 100%">
                <el-table-column prop="name" label="参数名" width="180">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.name"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="value" label="参数值" width="180">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.value"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="type" label="类型" width="180">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.type" placeholder="请选择">
                      <el-option label="String" value="string"></el-option>
                      <el-option label="Integer" value="integer"></el-option>
                      <el-option label="Boolean" value="boolean"></el-option>
                      <el-option label="Text" value="text"></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="说明">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.description"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100">
                  <template slot-scope="scope">
                    <el-button size="mini" type="danger" @click="handleDeleteParam(scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-button type="primary" @click="handleAddParam">添加参数</el-button> -->
            </el-form-item>
            <el-form-item :label="''" prop="header">
              <template slot="label">
                入参适配<br>（header）
              </template>
              <json_code v-model="toolForm.header" />
              <!-- 或者使用普通的文本区域 -->
              <!-- <el-input v-model="toolForm.body" type="textarea" :rows="4" placeholder="请输入JSON格式的body数据"></el-input> -->
            </el-form-item>
            <!-- 输入body的区域 -->
            <el-form-item :label="''" prop="body">
              <template slot="label">
                入参适配<br>（body）
              </template>
              <json_code v-model="toolForm.body" />
              <!-- 或者使用普通的文本区域 -->
              <!-- <el-input v-model="toolForm.body" type="textarea" :rows="4" placeholder="请输入JSON格式的body数据"></el-input> -->
            </el-form-item>

            <!-- 保存按钮 -->
            <el-form-item>
              <el-button type="primary" @click="submitForm">{{ $t('save') }}</el-button>
            </el-form-item>
            <!--
            <el-form-item :label="$t('template')+$t('type')" prop="type">
              <el-radio-group v-model="toolForm.type" @input="chooseType">
                <el-radio label="HelmChart" />
                <el-radio label="YAML" />
              </el-radio-group>
            </el-form-item>
            <el-form-item :label="$t('template')" prop="template">
              <el-select v-model="toolForm.template" :placeholder="$t('please')+$t('choose')+$t('template')" filterable style="width: 100%">
                <el-option
                  v-for="item in templateOptions"
                  :label="item.chartName + ' | ' + item.nickName"
                  :value="item.chartName"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('namespace')" prop="namespace">
              <el-select v-model="toolForm.namespace" :placeholder="$t('please')+$t('choose')+$t('namespace')" style="width: 100%">
                <el-option
                  v-for="ns in namespaceOptions"
                  :label="ns"
                  :value="ns"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('label')" prop="label">
              <el-checkbox-group v-model="toolForm.labels">
                <el-checkbox-button v-for="label in labels" :key="label.id" :label="label.id" style="margin: 0 5px 5px 0;">{{ label.name }}
                </el-checkbox-button>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleForm')">{{ $t('save') }}</el-button>
              <el-button @click="goBack">返回</el-button>
            </el-form-item>-->
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.create-container{
  background: #fff;
  padding-top: 20px;
}
</style>
